<template>
  <div class="cls1" ref="chartSC"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import china from '../assets/100000_full.json'
import { onMounted, ref } from 'vue'
// 大地图
import request from '../axios/request'
const chartSC = ref()
echarts.registerMap('china', china)

function chartsInit(data) {
  const myChart = echarts.init(chartSC.value, 'Light')
  myChart.showLoading()
  const formattedData = data.map((item) => ({ name: item.area, value: item.total_demand }))
  formattedData.sort((a, b) => a.value - b.value)
  const mapOption = {
    visualMap: {
      left: 'right',
      min: 0, // 根据原数据合理设置最小值，这里先设为0，可按需调整
      max: Math.max(...formattedData.map((item) => item.value)), // 根据数据实际最大值动态设置
      inRange: {
        // prettier-ignore
        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
      },
      text: ['High', 'Low'],
      calculable: true
    },
    series: [
      {
        id: 'population',
        type: 'map',
        roam: true,
        map: 'china',
        animationDurationUpdate: 1000,
        universalTransition: true,
        data: formattedData
      }
    ]
  }
  const barOption = {
    title: {
        text: '各地区分布地图', // 修改标题文本，更贴合饼图含义
        textStyle: {
          color: '#90E2FF',
          fontSize: 25,
          textAlign: 'center'
        },
        left: 'center',
        top: '5%'
      },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      axisLabel: {
        rotate: 30
      },
      data: formattedData.map((item) => item.name)
    },
    animationDurationUpdate: 1000,
    series: {
      type: 'bar',
      id: 'population',
      data: formattedData.map((item) => item.value),
      universalTransition: true
    }
  }
  let currentOption = mapOption
  myChart.setOption(mapOption)
  myChart.hideLoading()
  setInterval(() => {
    currentOption = currentOption === mapOption? barOption : mapOption
    myChart.setOption(currentOption, true)
  }, 2000)
}

// 组件挂载成功
onMounted(async function () {
  // 发起axios异步请求，获取数据
  request({
    url: '/produce-api/queryAllareanum', // 配置的代理请求会拦截
    method: 'get'
  }).then((res) => {
    console.log(res.data)
    chartsInit(res.data.data)
  }).catch((error) =>
    console.log(error))
})
</script>

<style scoped>
.cls1 {
  width: 100%;
  height: 100%;
}
</style>